package com.oceansoft.mobile.econsole.modules.api.controller;

import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.DateUtil;
import com.oceansoft.mobile.econsole.modules.accident.entity.AccidentInfo;
import com.oceansoft.mobile.econsole.modules.accident.entity.AccidentPhoto;
import com.oceansoft.mobile.econsole.modules.accident.service.IAccidentService;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.entity.Member;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 快撤理赔业务控制器
 *
 * @author: chenw
 * @time: 2014-8-17 12:19
 */
@RestController
@RequestMapping("api/accident")
public class ApiAccidentController extends BaseController {

    @Resource
    private IAccidentService accidentService;

    /**
     * 上报事故现场图片(三张)(photos)
     * 同时上传三张现场照片及事故地点坐标(coord)
     *
     * @param request MultipartHttpServletRequest
     * @return Result 生成事故上报业务流水号，在下一步提交时要将此流水号带入
     */
    @RequestMapping(value = "photos/upload", method = POST)
    public Result reportAccidentPhoto(MultipartHttpServletRequest request) {
        if (!DateUtil.between(configInfo.getAccidentAcceptStart(), configInfo.getAccidentAcceptEnd())) {
            return new Result(Result.FAILURE, "在线快撤理赔功能开放时间为" + configInfo.getAccidentAcceptStart() + ":00~" + configInfo.getAccidentAcceptEnd() + ":00");
        }
        try {
            return accidentService.saveAccidentBaseInfo(request);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "图片上传失败");
        }
    }

    /**
     * 上报事故现场图片(三张)(photos)
     * 图片Base64加密
     * 同时上传三张现场照片及事故地点坐标(coord)
     *
     * @param request HttpServletRequest
     * @return Result 生成事故上报业务流水号，在下一步提交时要将此流水号带入
     */
    @RequestMapping(value = "photos/place", method = POST)
    public Result reportAccidentPhotosPlace(HttpServletRequest request) {
        if (!DateUtil.between(configInfo.getAccidentAcceptStart(), configInfo.getAccidentAcceptEnd())) {
            return new Result(Result.FAILURE, "在线快撤理赔功能开放时间为" + configInfo.getAccidentAcceptStart() + ":00~" + configInfo.getAccidentAcceptEnd() + ":00");
        }
        try {
            return accidentService.saveAccidentPhotosPlace(request);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "图片上传失败");
        }
    }

    /**
     * 事故信息处理(双方自行协商1、远程定责2、理赔中心处理三种方式3)，用参数handler区分
     * 三种方式处理完成均需要生成流水号，上传的附件必须进入政务网闸及同时存储在服务器存盘文件
     * 在方式1、3同时需要发送短信通知
     *
     * @param request MultipartHttpServletRequest
     * @return Result 生成事故上报业务流水号，在下一步提交时要将此流水号带入
     */
    @RequestMapping(value = "info/process", method = POST)
    public Result reportAccidentInfo(MultipartHttpServletRequest request) {
        if (!DateUtil.between(configInfo.getAccidentAcceptStart(), configInfo.getAccidentAcceptEnd())) {
            return new Result(Result.FAILURE, "在线快撤理赔功能开放时间为" + configInfo.getAccidentAcceptStart() + ":00~" + configInfo.getAccidentAcceptEnd() + ":00");
        }
        String userId = request.getParameter("userId");
        if (!StringUtils.hasText(userId)) {
            return new Result(Result.FAILURE, "当前用户未登录！");
        }
        String accidentId = request.getParameter("accidentId");
        if (!StringUtils.hasText(accidentId)) {
            return new Result(Result.FAILURE, "快撤理赔流水号为空！");
        }
        String handler = request.getParameter("handler");
        if (null == handler || Constant.ZERO_STR.equals(handler))
            return new Result(Result.FAILURE, "请选择事故处理类型！");
        int handlerSwitch = Integer.valueOf(handler);
        switch (handlerSwitch) {
            case Constant.ACCIDENT_PROCESS_NEGOTIATE: //处理自行协商业务逻辑
                try {
                    return accidentService.processNegotiate(request);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return new Result(Result.FAILURE, "信息提交失败");
                }
            case Constant.ACCIDENT_PROCESS_REMOTE: //远程定责
                try {
                    return accidentService.doProcessRemote(userId, accidentId);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return new Result(Result.FAILURE, "信息提交失败");
                }
            case Constant.ACCIDENT_PROCESS_OFFICE://事故理赔中心处理
                try {
                    AccidentInfo info = new AccidentInfo();
                    info.setUserId(userId);
                    info.setAccidentId(accidentId);
                    info.setTelA(request.getParameter("telA"));
                    info.setTelB(request.getParameter("telB"));
                    info.setLicenseA(request.getParameter("licenseA"));
                    info.setLicenseB(request.getParameter("licenseB"));
                    return accidentService.doProcessOffice(info);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return new Result(Result.FAILURE, "信息提交失败");
                }
            default:
                return new Result(Result.FAILURE, "请选择事故处理类型！");
        }
    }

    /**
     * 取消事故信息上报
     *
     * @param userId     用户ID
     * @param accidentId 事故ID
     * @return Result
     */
    @RequestMapping(value = "report/revoke", method = POST)
    public Result revokeAccideintReport(@RequestParam(value = "uid", required = true) int userId,
                                        @RequestParam(value = "accidentId", required = true) String accidentId) {
        try {
            return accidentService.revokeAccidentReport(userId, accidentId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "事故上报信息撤回失败");
        }
    }

    /**
     * 加载用户历史事故信息
     */
    @RequestMapping(value = "history", method = POST)
    public Result getUserAccidentHistory(
            @RequestParam(value = "user_id", required = true) final int user_id,
            @RequestParam(value = "page_index", required = true) final int page_index,
            @RequestParam(value = "start_date", required = false) String start_date,
            @RequestParam(value = "end_date", required = false) String end_date,
            @RequestParam(value = "card_num", required = false) String card_num) {
        return accidentService.getUserAccidentHistory(user_id, page_index, start_date, end_date, card_num);
    }

    @RequestMapping(value = "accidentphotos", method = POST)
    public Result getAccidentPhotos(
            @RequestParam(value = "user_id", required = true) final int user_id,
            @RequestParam(value = "accident_id", required = true) String accident_id) {
        List<AccidentPhoto> list = accidentService.getAccidentPhotos(user_id, accident_id);
        if (list != null) {
            for (AccidentPhoto item : list) {
                item.setFilePath(configInfo.getFileDownloadUrl(item.getFilePath()));
            }
        }
        return new Result(true, list, "保险标志背面照获取成功");
    }
//    /**
//     * 快撤理赔上传图片
//     *
//     * @return Result
//     */
//    @Deprecated
//    @RequestMapping(value = "photo/upload", method = POST)
//    public Result uploadAccidentPicture(MultipartHttpServletRequest request) {
//        if (!DateUtil.between(configInfo.getAccidentAcceptStart(), configInfo.getAccidentAcceptEnd())) {
//            return new Result(Result.FAILURE, "在线快撤理赔功能开放时间为" + configInfo.getAccidentAcceptStart() + ":00~" + configInfo.getAccidentAcceptEnd() + ":00");
//        }
//        //附件信息
//        List<MultipartFile> mps = request.getFiles("photoFile");
//        if (mps.size() == 0)
//            return new Result(Result.FAILURE, "请选择事故图片");
//        if (mps.size() > 1) {
//            return new Result(Result.FAILURE, "一次上传单张图片");
//        }
//        AccidentPhoto photo = new AccidentPhoto();
//        photo.setUserId(request.getParameter("userId"));
//        photo.setAccidentId(request.getParameter("accidentId"));
//        photo.setPhotoGuid(request.getParameter("photoGuid"));
//        String _photoType = request.getParameter("photoType");
//        photo.setPhotoType(StringUtils.hasText(_photoType) ? Integer.parseInt(_photoType) : 1);//图片类型
//        photo.setCoordinate(request.getParameter("coordinate"));
//        photo.setPosition(request.getParameter("position"));
//        //拍照时间
//        String _shootTime = request.getParameter("shootTime");
//        Calendar cal = Calendar.getInstance();
//        cal.setTimeInMillis(StringUtils.hasText(_shootTime) ? Long.parseLong(_shootTime) : System.currentTimeMillis());
//        photo.setShootTime(cal.getTime());
//        photo.setTakerName(request.getParameter("takerName"));//拍照人姓名
//        //保存相对路径
//        String dataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        String realPath = String.format("%s/%s/%s", photo.getUserId(), dataStr, Constant.ACCIDENT);
//        photo.setFilePath(realPath);
//        MultipartFile mp = mps.get(0);
//        try {
//            String photoName = mp.getOriginalFilename();
//            photo.setPhotoName(photoName);
//            photo.setSize(mp.getSize());
//            //保存后缀
//            photo.setSuffix(photoName.substring(photoName.lastIndexOf(".")));
////            String extName = com.oceansoft.mobile.econsole.common.util.FileUtils.getExtName(mp.getOriginalFilename());
//            if (StringUtils.hasText(photo.getPhotoGuid()) && photo.getPhotoType() > 0 && accidentService.countSameTypePic(photo) > 0) { //同类型图片已经存在
//                photo.setFileContent(mp.getBytes());
//                accidentService.updatePhoto(photo);
//                return new Result(Result.SUCC, photo.getPhotoGuid(), "图片更新成功");
//            } else { //新增
//                photo.setPhotoGuid(DigestUtils.md5DigestAsHex(mp.getBytes()));
////                String newsFileName = photo.getPhotoGuid() + extName;//图片重新生成名称
//                photo.setFileContent(mp.getBytes());
//                accidentService.savePhoto(photo);
//                return new Result(Result.SUCC, photo.getPhotoGuid(), "图片上传成功");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            return new Result(Result.FAILURE, "图片信息保存失败");
//        }
//    }
}
